package com.atguigu.dao.impl;

import com.atguigu.pojo.Food;
import com.atguigu.utils.JDBCUtils;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public abstract class baseDao<T> {
    private Class<T> clazz = null;

    {
        //  获取当前baseDAO的子类继承的父类中的泛型
        Type genericSuperclass = this.getClass().getGenericSuperclass();
        ParameterizedType paramType = (ParameterizedType) genericSuperclass;
        Type[] typeArguments = paramType.getActualTypeArguments();
        clazz = (Class<T>) typeArguments[0];
    }

    //通用的增删改操作      version2.0
    public void update(String sql, Object... args) {
        PreparedStatement ps = null;
        Connection conn = null;
        try {
            conn = JDBCUtils.getConnection();
            //1.预编译SQL语句，返回prepareStatement的实例
            ps = conn.prepareStatement(sql);
            //2.填充占位符
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }
            //3.执行操作
            ps.execute();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);   // 将异常往外抛
            // 这里不能将conn关闭，关闭操作只能在事务提交的时候关闭
        }
    }

    //通用的查询操作、返回单条记录
    public T getInstance(String sql, Object... args) {
        //预编译SQL语句，返回PrepareStatement的实例
        PreparedStatement ps = null;
        ResultSet rs = null;
        Connection conn = null;
        try {
            conn = JDBCUtils.getConnection();
            ps = conn.prepareStatement(sql);
            //填充占位符
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }
            rs = ps.executeQuery();
            //获取结果集的元数据：ResultSetMetaData
            java.sql.ResultSetMetaData rsmd = rs.getMetaData();
            //获取结果集的列数
            int columnCount = rsmd.getColumnCount();
            if (rs.next()) {
                T t = clazz.newInstance();
                for (int i = 0; i < columnCount; i++) {
                    //获取列值
                    Object columnValues = rs.getObject(i + 1);
                    //获取列的别名
                    String columnLabel = rsmd.getColumnLabel(i + 1);
                    //给teacher对象指定的columnName赋值，赋值为columnValues，通过反射
                    Field field = t.getClass().getDeclaredField(columnLabel);
                    field.setAccessible(true);
                    field.set(t, columnValues);
                }
                return t;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);   // 将异常往外抛
            // 这里不能将conn关闭，关闭操作只能在事务提交的时候关闭
        }
        return null;
    }

    //通用的查询操作、返回多条记录
    public List<T> getForList(String sql) {
        //预编译SQL语句，返回PrepareStatement的实例
        PreparedStatement ps = null;
        ResultSet rs = null;
        Connection conn = null;
        try {
            conn = JDBCUtils.getConnection();
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            //获取结果集的元数据：ResultSetMetaData
            java.sql.ResultSetMetaData rsmd = rs.getMetaData();
            //获取结果集的列数
            int columnCount = rsmd.getColumnCount();
            ArrayList<T> list = new ArrayList<T>();
            while (rs.next()) {
                T t = clazz.newInstance();
                for (int i = 0; i < columnCount; i++) {
                    //获取列值
                    Object columnValues = rs.getObject(i + 1);
                    //获取列的别名
                    String columnLabel = rsmd.getColumnLabel(i + 1);
                    //给teacher对象指定的columnName赋值，赋值为columnValues，通过反射
                    Field field = clazz.getDeclaredField(columnLabel);
                    field.setAccessible(true);
                    field.set(t, columnValues);
                }
                list.add(t);
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);   // 将异常往外抛
            // 这里不能将conn关闭，关闭操作只能在事务提交的时候关闭
        }
    }

    //查询表中有多少条记录(主要针对于特殊函数的使用：count(*),max(*)...)
    public <E> E getValue(String sql, Object... args) {
        PreparedStatement ps = null;
        ResultSet rs = null;
        Connection conn = null;
        try {
            conn = JDBCUtils.getConnection();
            ps = conn.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }
            rs = ps.executeQuery();
            if (rs.next()) {
                return (E) rs.getObject(1);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);   // 将异常往外抛
            // 这里不能将conn关闭，关闭操作只能在事务提交的时候关闭
        }
        return null;
    }

    //通用的查询操作、返回多条记录  分页使用、一个id对应多条记录
    public List<T> getForListLimit(String sql, Object... args) {
        //预编译SQL语句，返回PrepareStatement的实例
        PreparedStatement ps = null;
        ResultSet rs = null;
        Connection conn = null;
        try {
            conn = JDBCUtils.getConnection();
            ps = conn.prepareStatement(sql);
            //填充占位符
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }
            rs = ps.executeQuery();
            //获取结果集的元数据：ResultSetMetaData
            java.sql.ResultSetMetaData rsmd = rs.getMetaData();
            //获取结果集的列数
            int columnCount = rsmd.getColumnCount();
            ArrayList<T> list = new ArrayList<T>();
            while (rs.next()) {
                T t = clazz.newInstance();
                for (int i = 0; i < columnCount; i++) {
                    //获取列值
                    Object columnValues = rs.getObject(i + 1);
                    //获取列的别名
                    String columnLabel = rsmd.getColumnLabel(i + 1);
                    //给teacher对象指定的columnName赋值，赋值为columnValues，通过反射
                    Field field = clazz.getDeclaredField(columnLabel);
                    field.setAccessible(true);
                    field.set(t, columnValues);
                }
                list.add(t);
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);   // 将异常往外抛
            // 这里不能将conn关闭，关闭操作只能在事务提交的时候关闭
        }
    }
}
